(function (w) {
  Array.prototype.removeRepeatBuildingAndFLoor = function () {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  var auditCreate = new Vue({
    el: '#auditCreate',
    data: {
      contratdata: [],
      matchData: [], //下拉匹配数据
      isReceiveMatch: false,
      isRefundMatch: false,
      pics: [],
      filesUrl: [],
      memo: '',
      wCode: '',
      contractId: '',
      projectId: '',
      zlfName: '',
      ot: [],
      st: [],
      chargeData: [],
      todoList: [],
      newTodoList: [],
      receiveData: [],
      filesName: [],
      refundData: [],
      paymentData: [],
      upComeData: [], //代办事项
      upCome: '',
      imgData: [],
      receiveRefund: {
        expense_name: '租金',
        amount: '0',
        memo: '',
        type: 'R'
      }, //应收租金
      refundRent: {
        expense_name: '租金',
        amount: '0',
        memo: '',
        type: 'R'
      }, //应退租金
      deposit: '', //押金/保证金
      checkStatus: '',
      checkBoxList: [],
      charge: {
        expense_name: '',
        amount: '',
        memo: '',
        type: 'T',
      },
      payment: {
        expense_name: '',
        amount: '',
        memo: '',
        type: 'T'
      },
      sum: {
        paymentSum: 0,
        chargeSum: 0
      },
      matchData: [], // 模糊匹配的费项
      contractExpense: [], // 与合同相关的费项
      nowIndex: -100,
      showCharge: false,
      showPayment: false,
      showUpCome: false,
      uploadBtn: true,
      wfMoney: 0,
      yfMoney: 0,
      timeDate: false,
      isShowSubmitConfirm: false,
      withdrawDate: '', // 退租时间
      delFlag: false,
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数
      wpTotalNum: 0, // 工位总数
      totalArea: 0, // 单元总面积
      building: [], // 楼宇信息
      projectName: null, // 项目名
      unitOpenFlag: true,
      wpOpenFlag: true,
      stOpenFlag: true,
      validWithdraw: null,
      //20190705
      flag: false,
      ktflag: true,
      flowtype: '',
      expenditureList: [],
      regExpenditureList: [],
      tzDate: '',


      progress: '',
      fileList: [],

      contractId: hlUrlUtil.GetQueryString('id'),
      conflictBills: [],
    },
    filters: {
      formatNum: function (item) {
        if (item == '--') return '--'
        return hlNumberUtil.formatNum(item)
      },
      formatDate: function (time) {
        if (time === undefined) {
          return '--'
        }
        var date = new Date(time)
        return hlDateUtil.formatUTCDate(date, 'yyyy-MM-dd')
      },
    },
    computed: {
      total() {
        let result = 0;
        this.expenditureList.map((item, index) => {
          result += Number(item.expense_amount)
        })
        this.regExpenditureList.map(item => {
          result -= Number(item.expense_amount)
        })
        return result
      }
    },
    methods: {
      // 相关文件
      uploadFile: function () {
        if (this.progress) {
          hl.toast('文件尚未上传完成')
          return
        }
        $('.upload-file-button').trigger('click')
      },
      // 删除上传的文件
      delFileItem(index) {
        this.fileList.splice(index, 1)
      },
      // 根据退租日期生成退租结算信息
      getWithdrawDate() {
        this.checkBoxActive(1)
        let data = {
          withdraw_date: this.tzDate,
          contract_id: this.contractId
        }
        hlhttp.get({
          url: 'withdraw/balance_info/by_withdraw_date',
          data: data,
          success: res => {
            res.conflictBills.map(item => {
              item.expenses.map(single => {
                if (single.withdrawAmount) {
                  single.withdrawAmount.amountRefund = (Number(single.withdrawAmount.amountPayed) + Number(single.withdrawAmount.derateExpense) + Number(single.withdrawAmount.carryOverAmount) - Number(single.withdrawAmount.amountReceive)).toFixed(2)
                }
                if (single.amount) {
                  single.amount.amountRefund = (Number(single.amount.amountPayed) + Number(single.amount.derateExpense) + Number(single.amount.carryOverAmount) - Number(single.amount.amountReceive)).toFixed(2)
                }
              })
            })
            this.conflictBills = res.conflictBills || []

            this.refundData = this.refundData.filter(item => {
              return item.mac_flag == 'Y'
            })
            this.receiveData = this.receiveData.filter(item => {
              return item.mac_flag == 'Y'
            })


            if (res.withdrawRefundExpenses && res.withdrawRefundExpenses.length) {
              res.withdrawRefundExpenses.map(item => {
                if (item.amount > 0) {
                  this.refundData.push({
                    amount: item.amount,
                    expenditureId: item.expenditureId,
                    expense_name: item.expenseName,
                    flowtype: item.flowType,
                    memo: item.memo,
                    type: item.type,
                    rate: item.taxFee,
                    percentage: item.lateFee,
                    mac_flag: 'N',
                    isShow: true,
                  })
                }
                if (item.amount < 0) {
                  this.receiveData.push({
                    amount: item.amount,
                    expenditureId: item.expenditureId,
                    expense_name: item.expenseName,
                    flowtype: item.flowType,
                    memo: item.memo,
                    type: item.type,
                    mac_flag: 'N',
                    isShow: true,
                  })
                }
              })
            }
          }
        })
      },

      queryExpenditure(ops) {
        this.flag = false
        if (!ops.name) return
        ops.expense_name = ops.name
        ops.mac_flag = 'Y'
        ops.isShow = true
        ops.flowtype = this.flowtype
        if (this.flowtype == 'RC') {
          this.receiveData.push(ops)
        } else {
          this.refundData.push(ops)
        }
      },
      //获取退租创建验证
      validContractFn: function (id) {
        var is = this;
        hlhttp.put({
          url: 'bpm/check_project_use',
          data: {
            bpm_key: 'WT',
            project_id: id
          },
          success: function (res) {
            is.validWithdraw = res.flag
          }
        })
      },
      //验证数字
      ValDataNumber: function (i, num) {
        if (num != 0) {
          if (!Number(num)) {
            hl.toast('请填写数字')
            this.receiveData[i].amount = 0
          }
        }
      },
      // 获取合同单元信息
      getContractUnitsData: function () {
        var self = this;
        hlhttp.get({
          url: 'contract/units',
          data: {
            id: self.contractId
          },
          success: function (data) {
            // 单元
            var buildingData = self.dealWithUnitData(data)
            self.totalArea = buildingData.totalArea
            self.building = buildingData.building
            // 车位
            self.st = [];
            self.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            data.map(function (item) {
              if (item.positions && item.unitType === 'ST') {
                stTotalNum = stTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.st.push(item)
              }
              if (item.positions && item.unitType === 'WP') {
                wpTotalNum = wpTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.wp.push(item)
              }
            })
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      // 单元数据去重整合处理
      dealWithUnitData: function (unitsData) {
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function (_item) {
          if (_item.positions.length === 0) {
            units.push(_item)
          }
        })
        if (units.length === 0) {
          return {
            building: [],
            totalArea: 0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i < units.length; i++) {
          unit.push({
            buildingName: units[i].buildingName,
            floorNum: units[i].floorNum,
            floorName: units[i].floorName,
            unit: []
          })
        }
        var unitArr = unit.removeRepeatBuildingAndFLoor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j < unitArr.length; j++) {
          building.push({
            buildingName: unitArr[j].buildingName,
            floor: []
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum': unitArr[n].floorNum,
                'floorName': unitArr[n].floorName,
                'unit': unitArr[n].unit
              })
            }
          }
        }
        return {
          building: buildingArr,
          totalArea: totalArea
        }
      },
      // 查看出租资源详情信息
      checkDetailMes: function (type) {
        var self = this;
        if (type === 'unit') {
          if (self.unitOpenFlag === true) {
            self.unitOpenFlag = false
            return false
          }
          if (self.unitOpenFlag === false) {
            self.unitOpenFlag = true
            return false
          }
        }
        if (type === 'wp') {
          if (self.wpOpenFlag === true) {
            self.wpOpenFlag = false;
            return false;
          }
          if (self.wpOpenFlag === false) {
            self.wpOpenFlag = true
            return false;
          }
        }
        if (type === 'st') {
          if (self.stOpenFlag === true) {
            self.stOpenFlag = false
            return false;
          }
          if (self.stOpenFlag === false) {
            self.stOpenFlag = true
            return false;
          }
        }
      },
      //获取退租时间
      pageName: function (name) {
        window.localStorage.setItem('cname', name)
      },
      getTZdate: function () {

        var _this = this;
        $('.dt-dateControl').on('click', function () {
          var aflag = false;
          if (aflag) return;
          setTimeout(function () {
            _this.timeDate = true;
            if (_this.tzDate) return;
            hlhttp.get({
              url: 'contract/wp_bill_count,ape_bill_count',
              data: {
                contract_id: _this.contractId,
                withdraw_time: _this.tzDate
              },
              success: function (res) {
                aflag = true;
                _this.wfMoney = res.wp_bill_count
                _this.yfMoney = res.ape_bill_count
              }
            })
          }, 300);
        })
      },
      pushReceive: function (val) {
        if (this.chargeData.length === 1) {
          return false
        }
        this.flag = true
        this.flowtype = val
      },
      // 跳转合同详情
      goToContractDeatail: function () {
        hlUrlUtil.goTo('contractNewDeatil', {
          id: this.contractId,
          ddtab: true
        }, true)
      },
      //合并数组
      addReceive: function (i) {
        var _name = this.chargeData[0].expense_name;
        var _amount = this.chargeData[0].amount;
        var _memo = this.chargeData[0].memo;
        if (_name === '') {
          hl.toast('费项名不能为空')
          $('.receive-name').focus()
          return false
        }
        if (!hlNumberUtil.isPositiveNumber(_amount)) {
          hl.toast('费用必须为正数')
          $('.receive-amount').val('').focus()
          return false
        }
        for (var j = 0; j < this.receiveData.length; j++) {
          if (this.receiveData[j].expense_name == _name) {
            hl.toast('费项名不能重复')
            $('.receive-name').focus()
            return false;
          }
        }
        this.$set(this.$data, 'receiveData', this.receiveData.concat(this.chargeData))
        this.chargeData.splice(i, 1)
      },
      pushRefund: function (val) {
        if (this.paymentData.length === 1) {
          return false
        }
        this.flag = true
        this.flowtype = val
        // this.paymentData.push({
        //   expense_name: '',
        //   amount: '',
        //   memo: '',
        //   type: 'T',
        //   isShow: true
        // });
      },
      //获取费项数据
      getExpenseData: function () {
        var _this = this;
        var id = hlUrlUtil.GetQueryString('id')
        hlhttp.get({
          url: 'contract/expenses',
          data: {
            contract_id: id
          },
          success: function (data) {
            _this.contractExpense = data
          }
        })
      },
      //展示匹配的应收费项
      showMatchReceiveExpense: function () {
        if (this.matchData.length == 0) {
          this.isReceiveMatch = false
        } else {
          this.isReceiveMatch = true
        }
      },
      //隐藏匹配的应收费项
      hideMatchReceiveExpense: function () {
        this.isReceiveMatch = false
      },
      //展示匹配的应退费项
      showMatchRefundExpense: function () {
        if (this.matchData.length == 0) {
          this.isRefundMatch = false
        } else {
          this.isRefundMatch = true
        }
      },
      //隐藏匹配的应退费项
      hideMatchRefundExpense: function () {
        this.isRefundMatch = false
      },
      //选择应收费项
      selectedReceiveExpense: function (name, type) {
        this.chargeData[0].expense_name = name
        this.chargeData[0].type = type
        this.isReceiveMatch = false
      },
      //选择应退费项
      selectedRefundExpense: function (name, type) {
        this.paymentData[0].expense_name = name
        this.paymentData[0].type = type
        this.isRefundMatch = false
      },
      //匹配应收费项
      matchReceiveExpense: function (val, i) {
        var self = this
        self.contractExpense.map(function (item) {
          if (item.expenseName.indexOf(val) >= 0 && val) {
            self.matchData = []
            self.matchData.push(item)
            self.isReceiveMatch = true
          } else if (val == '') {
            self.matchData = []
            self.isReceiveMatch = false
          }
        })
      },
      //匹配应退费项
      matchRefundExpense: function (val, i) {
        var self = this
        self.contractExpense.map(function (item) {
          if (item.expenseName.indexOf(val) >= 0 && val) {
            self.matchData = []
            self.matchData.push(item)
            self.isRefundMatch = true
          } else if (val == '') {
            self.matchData = []
            self.isRefundMatch = false
          }
        })
      },
      //合并数组
      addRefund: function (i) {
        var _name = this.paymentData[0].expense_name;
        var _amount = this.paymentData[0].amount;
        var _memo = this.paymentData[0].memo;
        if (_name === '') {
          hl.toast('费项名不能为空')
          $('.receive-name').focus()
          return false
        }
        if (!hlNumberUtil.isPositiveNumber(_amount)) {
          hl.toast('费用必须为正数')
          $('.receive-amount').val('').focus()
          return false
        }
        for (var j = 0; j < this.refundData.length; j++) {
          if (this.refundData[j].expense_name == _name) {
            hl.toast('费项名不能重复')
            $('.refund-name').focus()
            return false;
          }
        }
        this.$set(this.$data, 'refundData', this.refundData.concat(this.paymentData))
        this.paymentData.splice(i, 1)
      },
      //删除待办事项
      delTodoItem: function (i) {
        this.todoList.splice(i, 1)
      },
      //弹出待办事项输入框
      showTodoIpt: function () {
        if (this.newTodoList.length === 1) {
          return false
        }
        this.newTodoList.push('');
      },
      // 取消
      cancelTodoIpt: function (i) {
        this.newTodoList.splice(i, 1)
      },
      // 添加
      addTodoItem: function (i) {
        if (!this.newTodoList[i]) {
          hl.toast('待办事项不能为空')
          return
        }
        this.$set(this.$data, 'todoList', this.todoList.concat(this.newTodoList[i]))
        this.newTodoList.splice(i, 1)
      },
      //代办事项
      addTodo: function () {
        if (this.upCome === '') {
          hl.toast('费项名不能为空');
          $('.receive-name').focus();
          return false
        }
        this.upComeData.push(this.upCome);
        this.upCome = '';
      },
      //删除当前选中行
      del: function (_data, dataIndex) {
        _data.splice(dataIndex, 1);
      },
      //选中状态
      checkBoxActive: function (_index) {
        for (var i = 0; i < this.checkBoxList.length; i++) {
          this.checkBoxList[i].className = ''
        }
        this.checkBoxList[_index].className = 'active';
        this.checkStatus = this.checkBoxList[_index].name;
      },
      //上传图片
      uploadImage: function () {
        var _self = this;
        if (_self.pics.length === 5) {
          hl.toast('最多只能上传5张图片')
          return false
        }
        imgupload('.upload-image', uploadUrl, function (src) {
          _self.pics.push(JSON.parse(src.response).url)
        })
      },
      //删除图片
      delImage: function (i) {
        this.pics.splice(i, 1)
      },
      //大图展示
      showBigImage: function (i) {
        $.imageShow(this.pics, i)
      },
      //删除文件
      // deleteFile: function (i) {
      //   this.files.splice(i, 1);
      //   this.filesUrl.splice(i, 1);
      //   this.filesName.splice(i, 1);
      // },
      fileUrl: function (_url) {
        location.href = _url
      },
      backLis: function () {
        hlUrlUtil.goTo('withdrawList', {
          ddtab: true
        });
      },
      submitData: function () {
        var self = this;
        var receiveData = [];
        var refundData = [];
        var beginDate = this.contratdata.beginDate;
        var endDate = this.contratdata.endDate;
        if (!self.tzDate) {
          hl.toast('尚未填写日期')
          return false
        }
        var hireDate = new Date(self.tzDate + ' 00:00:00').getTime();
        self.withdrawDate = self.tzDate;

        if (hireDate < beginDate || hireDate > endDate) {
          hl.toast('退租时间不在合同生效日期范围')
          return false
        }

        this.receiveData.map(function (_item) {
          var obj = {
            amount: _item.amount || "0",
            expense_name: _item.expense_name,
            memo: _item.memo || '#',
            type: _item.type,
            flow_type: _item.flowtype,
            expenditure_id: _item.expenditureId || '#',
            tax_percent: _item.rate ? _item.rate / 100 + '' : '#',
            late_fee_percent: _item.percentage / 100 + '',
            mac_flag: _item.mac_flag
          }
          receiveData.push(obj)
        })
        this.refundData.map(function (_item) {
          var obj = {
            amount: _item.amount || "0",
            expense_name: _item.expense_name,
            memo: _item.memo || '#',
            type: _item.type,
            flow_type: _item.flowtype,
            expenditure_id: _item.expenditureId || '#',
            tax_percent: _item.rate ? _item.rate / 100 + '' : '#',
            late_fee_percent: _item.percentage / 100 + '',
            mac_flag: _item.mac_flag
          }
          refundData.push(obj)
        })

        var data = {
          withdraw_date: this.tzDate,
          w_code: this.wCode,
          zlf_name: this.zlfName,
          project_id: this.projectId,
          contract_id: this.contractId,
          reason: this.checkStatus,
          todo_list: this.todoList.join(',') || '#',
          pics: this.pics.join(',') || '#',
          memo: this.memo || '#',
          receive: JSON.stringify(receiveData),
          refund: JSON.stringify(refundData),
        };

        return data
      },

      //合同终止校验
      checkWithout(val) {
        var that = this
        hlhttp.get({
          url: 'withdraw/_check',
          data: {
            'contract_id': that.contractId
          },
          success: function (res) {
            if (val == 'save') {
              that.saveWithdraw()
            } else {
              that.showSubmitConfirmLayer()
            }
          },
        })
      },
      // 保存文件
      saveFile(id) {
        if (!this.fileList.length) return
        let nameList = []
        let urlList = []
        this.fileList.map(item => {
          nameList.push(item.name)
          urlList.push(item.url)
        })

        let data = {
          withdraw_id: id,
          attachment_name: nameList + '',
          attachment_url: urlList + '',
        }
        hlhttp.post({
          url: 'withdraw_attachment',
          data: data,
          success: function (res) {

          },
        })
      },
      // 保存退租单
      saveWithdraw: function () {
        if (this.validWithdraw == 'N') {
          hl.toast('请先配置流程')
          return
        }
        var data = this.submitData()
        if (!this.submitData().withdraw_date) return
        console.log(data)
        // 保存退租单 退租单变为草稿状态
        hlhttp.post({
          data: data,
          url: 'withdraw',
          success: res => {
            hl.toast('保存成功')
            this.saveFile(res.id)
            setTimeout(function () {
              hlUrlUtil.goTo('withdrawList', {
                ddtab: true
              });
            }, 1000)
          }
        })
      },
      showSubmitConfirmLayer: function () {
        if (this.submitData()) {
          this.isShowSubmitConfirm = true;
        }
      },
      closeSubmitConfirmLayer: function () {
        this.isShowSubmitConfirm = false;
      },
      // 提交退租单
      confirmSubmitWithdraw: function () {
        var data = this.submitData()
        // 提交退租单 退租单变为待审核状态
        hlhttp.post({
          data: data,
          url: 'withdraw/_submit',
          success: res => {
            this.saveFile(res.id)
            loginPrem.loginList()
            hlUrlUtil.goTo('withdrawList', {
              ddtab: true
            });
          }
        })
      }
    },
    computed: {
      chargeTotal: function () {
        var sum = 0;
        for (var i = 0; i < this.receiveData.length; i++) {
          sum += Number(this.receiveData[i].amount);
        }
        this.sum.chargeSum = sum.toFixed(2);
        return sum.toFixed(2);
      },
      paymentTotal: function () {
        var sum = 0;
        for (var i = 0; i < this.refundData.length; i++) {
          sum += Number(this.refundData[i].amount);
        }
        this.sum.paymentSum = sum.toFixed(2);
        return sum.toFixed(2);
      },
      total: function () {
        var all = this.sum.chargeSum - this.sum.paymentSum;
        if (all < 0) {
          return hlNumberUtil.formatNum(Math.abs(all)) + '元（应退）'
        } else if (all > 0) {
          return hlNumberUtil.formatNum(all) + '元（应付）'
        } else {
          return hlNumberUtil.formatNum(all) + '元'
        }
      }
    },
    mounted: function () {
      this.uploadImage();
      this.getExpenseData();
      loginPrem.loginList()
      this.getTZdate()
      var _this = this
      fileUpload('.upload-file-button', uploadUrl, function (res) {
        _this.progress = ''
        _this.fileList.push(res.json)
      }, function (val) {
        _this.progress = parseInt((val.loaded / val.total) * 100) + '%'
      })
    },
    beforeMount: function () {
      var _this = this;
      var id = hlUrlUtil.GetQueryString('id')
      //获取id
      contract.formatUnitData(id, function (data) {
        _this.contratdata = data;
        // _this.refundData[1].amount = data.deposit.toString();
        _this.contractId = data.contractId;
        _this.projectId = data.projectId;
        _this.zlfName = data.zlfCompany;
        _this.st = data.st;
        _this.ot = data.ot;
        _this.validContractFn(data.projectId)
        _this.getContractUnitsData()
      });
      hlhttp.get({
        url: 'withdraw/w_code',
        success: function (res) {
          _this.wCode = res.wCode

        }
      })
      hlhttp.get({
        url: 'withdraw_reasons', //退租原因列表
        success: function (res) {
          for (var i = 0; i < res.length; i++) {
            _this.checkBoxList.push({
              name: res[i],
              rel: i,
              className: ''
            })
            _this.checkBoxList[0].className = 'active'
          }
          _this.checkStatus = _this.checkBoxList[0].name
        }
      })
    }
  })



}());